package com.example.demo.utils;

import com.example.demo.exception.ExceptionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils {


    private volatile static ObjectMapper objectMapper;

    private JsonUtils() {
        throw new IllegalStateException("Utils");
    }

    public static ObjectMapper getInstance() {
        if (objectMapper == null) {
            synchronized (JsonUtils.class) {
                if (objectMapper == null) {
                    objectMapper = new ObjectMapper();
                }
            }
        }
        return objectMapper;
    }

    public static <T> T deserialize(String json, Class<T> clazz) {
        try {
            return getInstance().readValue(json, clazz);
        } catch (IOException e) {
            throw ExceptionUtils.exception(clazz + "类型对象解析出错", e);
        }
    }

    public static <T> List<T> deserializeList(String json, Class<T> clazz) {
        try {
            if (StringUtils.isBlank(json)) {
                return new ArrayList<>();
            } else {
                ObjectMapper instance = getInstance();
                CollectionType type = instance.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
                return instance.readValue(json, type);
            }
        } catch (IOException e) {
            throw ExceptionUtils.exception(clazz + "类型对象集合反序列化出错", e);
        }
    }

    public static String serialize(Object value) {
        try {
            return value == null ? null : getInstance().writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw ExceptionUtils.exception(value.getClass() + "类型对象解析出错", e);
        }
    }
}